package com.wqr.mobile.android.ui.fragment;

import java.util.List;

import android.content.Context;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.wqr.mobile.android.ui.R;
import com.wqr.mobile.android.ui.adapter.MBaseAdapter;
import com.wqr.mobile.android.ui.api.API;
import com.wqr.mobile.android.ui.bean.WeiboSearch;
import com.wqr.mobile.android.ui.bean.WeiboSearch.WeiboUser;
import com.wqr.mobile.android.ui.bean.WeiboUserHolder;
import com.wqr.mobile.android.ui.net.ImageDownloader;
import com.wqr.mobile.android.ui.net.NetworkManager;
import com.wqr.mobile.android.ui.task.HttpRequestTask;
import com.wqr.mobile.android.ui.task.HttpRequestTask.HttpTaskCallBack;
import com.wqr.mobile.android.ui.task.HttpTaskResult;
import com.wqr.mobile.android.ui.utils.JsonUtil;
import com.wqr.mobile.android.ui.widget.PullToRefreshView;
import com.wqr.mobile.android.ui.widget.PullToRefreshView.OnFooterRefreshListener;
import com.wqr.mobile.android.ui.widget.PullToRefreshView.OnHeaderRefreshListener;

public class WeboFragmentList extends Fragment implements OnScrollListener, API, Callback, HttpTaskCallBack,
		OnHeaderRefreshListener, OnFooterRefreshListener {
	private static final String TAG = WeboFragmentList.class.getSimpleName();
	private static final int SCROLL_FINISHED = 0;
	private PullToRefreshView mPullToRefreshView;
	private ListView mlistView;
	private Handler mHandler;

	private Context mContext;
	private MBaseAdapter<WeiboUser, WeiboUserHolder> mAdapter;
	private HttpRequestTask mImageTask;
	private NetworkManager mNetworkManager;
	private ImageDownloader mImagedownloader;

	private String next_page = "q=";
	private int getLastVisiblePosition = 0, lastVisiblePositionY = 0;
	private boolean lock;

	public WeboFragmentList(String star) {
		next_page = next_page + star;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = getActivity();
		mHandler = new Handler(this);
		loadApplist();
	}

	private void loadApplist() {
		if (!lock) {
			mImageTask = new HttpRequestTask(this);
			mImageTask.execute(next_page);
			lock = true;
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mPullToRefreshView = (PullToRefreshView) inflater.inflate(R.layout.activity_list, null);
		mPullToRefreshView.setOnFooterRefreshListener(this);
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mlistView = (ListView) mPullToRefreshView.findViewById(R.id.list);
		return mPullToRefreshView;
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
		// // 滚动到底部
		// if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
		// View v = view.getChildAt(view.getChildCount() - 1);
		// int[] location = new int[2];
		// v.getLocationOnScreen(location);// 获取在整个屏幕内的绝对坐标
		// int y = location[1];
		// if (view.getLastVisiblePosition() != getLastVisiblePosition && lastVisiblePositionY != y)// 第一次拖至底部
		// {
		// // mLoadItem.setVisibility(View.VISIBLE);
		// getLastVisiblePosition = view.getLastVisiblePosition();
		// lastVisiblePositionY = y;
		// loadApplist();
		// return;
		// }
		// }
		//
		// // 未滚动到底部，第二次拖至底部都初始化
		// getLastVisiblePosition = 0;
		// lastVisiblePositionY = 0;
		// }

	}

	@Override
	public void onTaskStart() {
		// TODO Auto-generated method stub

	}

	@Override
	public HttpTaskResult onTaskRunning(Object... params) {
		String message = (String) params[0];
		if (mNetworkManager == null) {
			mNetworkManager = NetworkManager.getInstance();
		}
		return new HttpTaskResult(message, mNetworkManager.getRequest(mContext, next_page, WEIBO_SEARCH));
	}

	@Override
	public void onCancelled(Status status) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTaskFinished(HttpTaskResult result) {
		if (result != null && result.getResult() != null) {
			WeiboSearch data = JsonUtil.TransformJson2Vo(result.getResult(), WeiboSearch.class);
			if (data != null) {
				next_page = data.next_page.replace("?", "&");
				if (mAdapter == null) {
					createAdapter(data.results);
				} else {
					mAdapter.addList(data.results);
					mHandler.sendEmptyMessage(SCROLL_FINISHED);
				}
			}
		}

		lock = false;
	}

	private void createAdapter(List<WeiboUser> mUsers) {
		if (mImagedownloader == null) {
			mImagedownloader = new ImageDownloader(mContext);
		}
		mAdapter = new MBaseAdapter<WeiboUser, WeiboUserHolder>(mContext, R.layout.layout_weibo_search_item,
				new WeiboUserHolder(), mUsers) {

			@Override
			public void findHolderViews(View convertView, WeiboUserHolder holder) {
				holder.item_icon = (ImageView) convertView.findViewById(R.id.item_icon);
				holder.created_at = (TextView) convertView.findViewById(R.id.item_created_at);
				holder.item_text = (TextView) convertView.findViewById(R.id.item_text);
				holder.item_toUser = (TextView) convertView.findViewById(R.id.item_toUser);
				holder.item_user = (TextView) convertView.findViewById(R.id.item_user);
			}

			@Override
			public void setItemFromHolder(WeiboUserHolder holder, WeiboUser item) {
				mImagedownloader.download(item.profile_image_url, holder.item_icon);
				holder.created_at.setText(item.created_at);
				holder.item_text.setText(item.text);
				holder.item_toUser.setText(item.to_user);
				holder.item_user.setText(item.from_user);
			}

			@Override
			public void _onItemClick(Context context, AdapterView<?> parent, View view, int position, long id, WeiboUser item) {
				Toast.makeText(mContext, item.toString(), 1).show();
			}
		};
		mHandler.sendEmptyMessage(FINISHED);
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case FINISHED:
			mlistView.setAdapter(mAdapter);
			mAdapter.setOnItemClickListener(mlistView);
			mlistView.setOnScrollListener(this);
			break;
		case SCROLL_FINISHED:
			mPullToRefreshView.onFooterRefreshComplete();
			break;

		default:
			break;
		}
		return false;
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		loadApplist();
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				// 设置更新时间
				// mPullToRefreshView.onHeaderRefreshComplete("最近更新:01-23 12:01");
				mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1000);
	}
}
